package me.sealer.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能描述： $ ClassUtil 获取类机器父类中中所有非static非transient字段。
 *
 * @author sealer
 * @email 1178884049@qq.com
 * @date 2019年08月07日 15时21分59秒
 */
public class ClassUtil {
    public static <T> Field[] getAllFieldsForJdk8(Class<T> clazz) {
        Class c = clazz;
        List<Field> fieldList = new ArrayList<>();
        while (c != null) {
            List<Field> fList = Arrays.stream(c.getDeclaredFields())
                    .filter(field -> {
                        int mod = field.getModifiers();
                        return !Modifier.isTransient(mod) && !Modifier.isStatic(mod);
                    })
                    .collect(Collectors.toList());

            fieldList.addAll(fList);
            c = c.getSuperclass();

        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        Arrays.sort(fields, Comparator.comparing(Field::getName));
        return fields;
    }

    public static Field[] getAllFieldsForJdk5(Class clazz) {
        Class c = clazz;
        List fieldList = new ArrayList();
        while (c != null) {
            for (Field f : c.getDeclaredFields()) {
                int mod = f.getModifiers();
                if (!Modifier.isTransient(mod) && !Modifier.isStatic(mod)) {
                    fieldList.add(f);
                }
            }

            c = c.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        Arrays.sort(fields, new Comparator<Field>() {
            @Override
            public int compare(Field o1, Field o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        return fields;
    }

    public static void main(String[] args) {
        Field[] fields = getAllFieldsForJdk5(String.class);
        Arrays.stream(fields)
                .forEach(field -> System.out.println(field.getName() + "---" + field.getType().getName()));
    }
}
